package com.zsc.wxm.ysh.anjo.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取ip地址
 * @author playmaker
 */
public class IpUtil {

    public IpUtil() {

    }

    private static final String UNKNOWN = "unknown";

    private static String x_forwarded_for = "x-forwarded-for";
    private static String proxy_client_ip = "Proxy-Client-IP";
    private static String X_forwarded_for = "X-Forwarded-For";
    private static String wl_proxy_client_ip = "WL-Proxy-Client-IP";
    private static String x_real_ip = "X-Real-IP";

    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        if (request == null) {
            return UNKNOWN;
        }
        try {
            ip = request.getHeader(x_forwarded_for);

            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(proxy_client_ip);
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(X_forwarded_for);
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(wl_proxy_client_ip);
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(x_real_ip);
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if ("127.0.0.1".equals(ip)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    assert inet != null;
                    ip = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ip != null && ip.length() > 15) {
                // = 15
                if (ip.indexOf(",") > 0) {
                    ip = ip.substring(0, ip.indexOf(","));
                }
            }
        } catch (Exception e) {
            ip = null;
        }

        return ip;
    }


}
